package com.itheima.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class MpConfig {

    //1.将MybatisPlusInterceptor放入到spring容器中
    @Bean
    MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    //MetaObjectHandler: 元对象处理器
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            //当做insert 操作时候，给指定的字段赋值
            @Override
            public void insertFill(MetaObject metaObject) {
                Date now = new Date();
                //insert操作的时候向封装的实体对象中填充creatTime、updateTime字段的值
                this.strictInsertFill(metaObject, "createTime", Date.class, now);
                this.strictInsertFill(metaObject, "updateTime", Date.class, now);
            }

            //当做update 操作时候，给指定的字段赋值
            @Override
            public void updateFill(MetaObject metaObject) {
                Date now = new Date();
                //update操作的时候向封装的实体对象中填充updateTime字段的值
                this.strictUpdateFill(metaObject, "updateTime", Date.class, now);
            }
        };
    }

}
